import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useAppStore = defineStore('app', () => {
  // 状态定义
  const loading = ref(false)
  const globalLoading = ref(false)
  const theme = ref('light')
  const networkStatus = ref(navigator.onLine)
  const appVersion = ref('1.0.0')
  const debugMode = ref(false)

  // 页面加载状态管理
  const pageLoadingStates = ref(new Map())

  // 计算属性
  const isOnline = computed(() => networkStatus.value)
  const isOffline = computed(() => !networkStatus.value)
  const isDarkTheme = computed(() => theme.value === 'dark')
  const isLightTheme = computed(() => theme.value === 'light')

  // 是否有任何页面在加载
  const hasPageLoading = computed(() => {
    return Array.from(pageLoadingStates.value.values()).some(loading => loading)
  })

  // Actions
  const setLoading = (isLoading) => {
    loading.value = isLoading
  }

  const setGlobalLoading = (isLoading) => {
    globalLoading.value = isLoading
  }

  const setPageLoading = (pageKey, isLoading) => {
    if (isLoading) {
      pageLoadingStates.value.set(pageKey, true)
    } else {
      pageLoadingStates.value.delete(pageKey)
    }
  }

  const setTheme = (newTheme) => {
    if (['light', 'dark'].includes(newTheme)) {
      theme.value = newTheme
      localStorage.setItem('app_theme', newTheme)
      
      // 应用主题到document
      document.documentElement.setAttribute('data-theme', newTheme)
    }
  }

  const toggleTheme = () => {
    const newTheme = theme.value === 'light' ? 'dark' : 'light'
    setTheme(newTheme)
  }

  const updateNetworkStatus = (status) => {
    networkStatus.value = status
  }

  const setDebugMode = (enabled) => {
    debugMode.value = enabled
    localStorage.setItem('debug_mode', enabled.toString())
  }

  const toggleDebugMode = () => {
    setDebugMode(!debugMode.value)
  }

  // 初始化应用状态
  const initAppState = () => {
    try {
      // 恢复主题设置
      const savedTheme = localStorage.getItem('app_theme')
      if (savedTheme && ['light', 'dark'].includes(savedTheme)) {
        setTheme(savedTheme)
      }

      // 恢复调试模式设置
      const savedDebugMode = localStorage.getItem('debug_mode')
      if (savedDebugMode) {
        debugMode.value = savedDebugMode === 'true'
      }

      // 监听网络状态变化
      window.addEventListener('online', () => updateNetworkStatus(true))
      window.addEventListener('offline', () => updateNetworkStatus(false))
    } catch (error) {
      console.error('初始化应用状态失败:', error)
    }
  }

  // 清理应用状态
  const cleanup = () => {
    window.removeEventListener('online', () => updateNetworkStatus(true))
    window.removeEventListener('offline', () => updateNetworkStatus(false))
  }

  // 获取应用信息
  const getAppInfo = () => {
    return {
      version: appVersion.value,
      theme: theme.value,
      isOnline: isOnline.value,
      debugMode: debugMode.value,
      userAgent: navigator.userAgent,
      platform: navigator.platform,
      language: navigator.language
    }
  }

  // 错误处理
  const handleError = (error, context = '') => {
    console.error(`应用错误 ${context}:`, error)
    
    if (debugMode.value) {
      // 在调试模式下显示更详细的错误信息
      console.trace('错误堆栈:', error)
    }
    
    // 可以在这里添加错误上报逻辑
    return {
      message: error.message || '未知错误',
      context,
      timestamp: new Date().toISOString()
    }
  }

  // 性能监控
  const performanceMetrics = ref({
    pageLoadTime: 0,
    apiResponseTimes: new Map(),
    memoryUsage: 0
  })

  const recordPageLoadTime = (time) => {
    performanceMetrics.value.pageLoadTime = time
  }

  const recordApiResponseTime = (apiName, time) => {
    performanceMetrics.value.apiResponseTimes.set(apiName, time)
  }

  const updateMemoryUsage = () => {
    if (performance.memory) {
      performanceMetrics.value.memoryUsage = performance.memory.usedJSHeapSize
    }
  }

  // 初始化时自动设置应用状态
  initAppState()

  return {
    // 状态
    loading,
    globalLoading,
    theme,
    networkStatus,
    appVersion,
    debugMode,
    pageLoadingStates,
    performanceMetrics,
    
    // 计算属性
    isOnline,
    isOffline,
    isDarkTheme,
    isLightTheme,
    hasPageLoading,
    
    // Actions
    setLoading,
    setGlobalLoading,
    setPageLoading,
    setTheme,
    toggleTheme,
    updateNetworkStatus,
    setDebugMode,
    toggleDebugMode,
    initAppState,
    cleanup,
    getAppInfo,
    handleError,
    recordPageLoadTime,
    recordApiResponseTime,
    updateMemoryUsage
  }
})
